<template>
  <div>
    <div class="search-term">
    <el-form :inline="true" :model="searchInfo">
      <el-form-item label="应用">
        <el-select clearable filterable placeholder="请选择" v-model="searchInfo.apps_name" @change="getVersion">
        <el-option
                v-for="(item, i) in appOptions"
                :key=i
                :label=item
                :value=item>
        </el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="回滚版本">
<!--        <el-select clearable filterable placeholder="请选择" v-model="searchInfo.version" @change="showTagInfo">-->
        <el-select clearable filterable placeholder="请选择" v-model="searchInfo.version">
          <el-option
                  v-for="(item, i) in buildHistoryList"
                  :key=i
                  :label=item.version
                  :value=item.version>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                :disabled="disabledBuild"
                @click="handleRollbackBtn"
        >开始回滚</el-button>
      </el-form-item>
    </el-form>
  </div>
    <div>
        只支持生产环境回滚
        <p v-if="searchInfo.apps_job_name.indexOf('prod-') != -1 && searchInfo.version != ''" class="rollback-tip">{{tagInfo}}</p>
    </div>
    <div class="console">
      <!--      vue/no-textarea-mustache 在eslint检测中会有告警 这里忽略-->
      <textarea class="log" id="logArea"  placeholder="" :value="`${buildLogTitle}${buildLogContent}`">

      </textarea>
    </div>
  </div>
</template>

<script>
  /* eslint-disable */
  import { getDeployBuildList } from "@/api/deploy_build";
  import { getDeployAppList } from "@/api/deploy_app";
  import { rollbackJenkinsJobBuild, getJenkinsBuildJobLogs } from "@/api/deploy_jenkins";

  export default {
    name: "rollback",
    data() {
      return {
        searchInfo: {
          apps_job_name: '',
          apps_name: '',   // 默认前端只使用apps_name 但是也支持输入job名字 留给回滚dev/test/uat入口
          version: '',
        },
        appOptions: [],
        tagInfo: '',
        deploy_type: "rollback", // 回滚
        buildHistoryList: [],
        disabledBuild:false,
        buildLogTitle: '支持后端、前端回滚\n回滚提示：回滚过程不要断开浏览器，如断开需要查看回滚日志请到发布历史中查看',
        buildLogContent: '',
      }
    },
    methods: {
      getJenkinsBuildJobLogs(build_number, apps_job_name) {
        getJenkinsBuildJobLogs({build_number: build_number, apps_job_name: apps_job_name, deploy_type: this.deploy_type}).then(res => {
          if (res.code == 0 ) {
            this.buildLogContent = res.data.log
          }
        })
      },
      handleRollbackBtn() {
        this.$confirm("是否确定要回滚?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.visible = false;
            this.handleRollback()
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消回滚"
            });
          });
      },
      handleRollback() {
        // console.log('开始回滚')
        rollbackJenkinsJobBuild({apps_job_name:this.searchInfo.apps_job_name, "version": this.searchInfo.version, deploy_type: this.deploy_type}).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '回滚触发成功，等待回滚，请关注日志',
            })
            // 禁用回滚按钮
            this.disabledBuild = true
            // 获取日志

            this.buildLogTitle = '等待执行中，本次回滚日志:\n'
            // 打开websocket
            this.openWS(res.data.build_number, this.searchInfo.apps_job_name)

          }
        })
      },
      getVersion() {
        this.searchInfo.version = ''
        // 默认只回滚生产环境
        if (this.searchInfo.apps_name.match(/^dev-|^test-|^uat-|^prod-/) == null) {
          this.searchInfo.apps_job_name = "prod-" + this.searchInfo.apps_name
        } else {
          this.searchInfo.apps_job_name = this.searchInfo.apps_name
        }
        // console.log(this.searchInfo.apps_job_name)
        if (this.searchInfo.apps_job_name != "") {
          getDeployBuildList({page:1, pageSize:10, apps_job_name:this.searchInfo.apps_job_name, deploy_type: "normal"}).then(res => {
            if (res.code == 0 ) {
              // console.log(res.data.list)
              // 过滤出发布成功的版本 - 可以作为回滚的版本
              this.buildHistoryList = res.data.list.filter( x => {return x.deploy_status == "2"}).map(x => {return {"version": x.version, "tag_info": x.tag_info}})
              // console.log(this.buildHistoryList)
            } else {
              this.$message({
                type: 'error',
                message: '网络请求失败',
              })
            }
          })
        }
      },
      showTagInfo() {
        this.tagInfo = this.buildHistoryList.filter(x => {return x.version == this.searchInfo.version})[0].tag_info
        // console.log(this.searchInfo.version, this.buildHistoryList,"-----",this.tagInfo)
      },
      openWS(build_number, apps_job_name) {
        this.ws = new WebSocket(`ws://${location.hostname}:8081/base/deploy/jenkins/getJenkinsBuildJobLogsWS?apps_job_name=${apps_job_name}&build_number=${build_number}&deploy_type=${this.deploy_type}`);

        this.ws.onopen = (event) => {
          console.log('Ws Connection open', event);

        }
        this.ws.onclose = (event) =>   {
          console.log('Ws Connection closed',event);

        }

        // 使用箭头函数 但最简单的两种方法是使用箭头函数，它没有this绑定，因此允许您访问父级this
        this.ws.onmessage = (event) => {
          // console.log('build log updated');
          // console.log(event.data)
          // 每次事件给的都是全量数据
          this.buildLogContent = event.data
          if (this.buildLogContent.indexOf("Finished:") !== -1) {
            this.disabledBuild = false  // 完成构建放开回滚按钮
          }
        }

      },
    },
    created() {
      getDeployAppList({'page':1, 'pageSize':500}).then(res => {
        if (res.code == 0 ) {
          this.appOptions = res.data.list.map(x => {return x.apps_name})
        } else {
          this.$message({
            type: 'error',
            message: '网络请求失败',
          })
        }

      })

    }
  }
</script>

<style scoped>
  .log{
    width: 95%;
    line-height: 1.5em;
    height: 500px;
    resize: none;
    border: 1px solid #ddd;
    background: #000;
    color: #fff;
  }

  .rollback-tip {
    width: 95.5%;
    background-color: yellow;
    display: inline-block;
  }

</style>